import { useEffect, useState } from 'react';
import { MoviesModel } from '../model/MoviesModel';
import { fetchMovieDetails, fetchMoviesData } from './MoviesRepository';

// 定义状态接口
interface MoviesUIState {
  movies: MoviesModel | null;
  loading: boolean;
  error: Error | null;
}

const useMoviesState = () => {
  const [state, setState] = useState<MoviesUIState>({
    movies: null,
    loading: true,
    error: null,
  });

  const loadMovies = async () => {
    setState((prevState) => ({ ...prevState, loading: true }));
    try {
      const moviesEntity = await fetchMoviesData();
      console.log('获取数据:');
      setState({ movies: moviesEntity, loading: false, error: null });
    } catch (err) {
      setState((prevState) => ({
        ...prevState,
        loading: false,
        error: err as Error,
      }));
      console.error('获取数据时出错:', err);
    }
  };
  const loadMovieDetails = async (id: string) => {
    try {
      const details = await fetchMovieDetails(id);
      // 处理电影详细信息的逻辑
      console.log(details);
    } catch (err) {
      console.error('获取电影详情时出错:', err);
    }
  };
  useEffect(() => {
    loadMovies(); // 初次加载
  }, []);

  const refreshData = () => {
    loadMovies(); // 刷新数据
  };
  return { state, refreshData, loadMovieDetails }; // 返回状态和刷新方法
};
export default useMoviesState;
